/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import ferramentas.CFG;
import ferramentas.Query;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import pessoal.Usuario;

/**
 *
 * @author carlo
 */
public class documentoUsuario extends HttpServlet {

    private static final String TMP_DIR_PATH = System.getProperty("java.io.tmpdir");
    private File tmpDir = new File(TMP_DIR_PATH);
    private int MAX_SIZE_UPLOAD = 5 * 1024 * 1024; // 5Mb
    private String ENCODING = "UTF-8";

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {

            ServletFileUpload handler = getHandler();
            Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
            // Check that we have a file upload request
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                List items = getItemsRequest(request, handler);

                String legenda = getParameter("legenda", items);
                FileItem documentoUploaded = getFile("documento", items);
                int status = 0; //Indica que o documento acabou de ser inserido pela primeira vez
                if (!documentoUploaded.getName().equals("")) {
                    int curso = Integer.parseInt(getParameter("curso", items));
                    String caminhoArquivo = getPastaDocumentos(curso) + usuario.getCpf() + "_" + documentoUploaded.getName();
                    if (documentoUploaded.getName().endsWith(".exe") || documentoUploaded.getName().endsWith(".bat") || documentoUploaded.getName().endsWith(".pif")) {
                        out.println("<script>window.alert('O documento possui um formato incompatível com o esperado! Tente novamente.');history.go(-1);</script>");
                    } else {
                        if (!new File(getPastaDocumentos(curso)).exists()) { // Verifica se o diretório existe.   
                            new File(getPastaDocumentos(curso)).mkdir();   // Cria o diretório   
                        }
                        File arquivoDocumento = new File(caminhoArquivo);
                        documentoUploaded.write(arquivoDocumento);

                        int tipoCurso = Integer.parseInt(getParameter("tipoCurso", items));

                        String url = getEnderecoRelativoDocumentos(request, curso) + arquivoDocumento.getName();
                        Query q = new Query();
                        q.inserirDocumentoUsuario(legenda, url, usuario, status, curso);
                        out.println("<script>window.alert('Documento (" + legenda + ") inserido com sucesso!');location.href='index.jsp?conteudo=inscricao_documentos&curso=" + curso + "&tipo=" + tipoCurso + "';</script>");
                    }
                } else {
                    out.println("<script>window.alert('Operação não realizada! Verifique se você realmente escolheu um arquivo e tente novamente, se o problema persistir entre em contato com o Administrador.');history.go(-1);</script>");
                }
            } else {
                out.println("<script>window.alert('Erro ao enviar documento!');history.go(-1);</script>");
            }
        } catch (Exception e) {
            if (e instanceof FileUploadException) {
                out.println("<script>window.alert('O tamanho do arquivo a ser inserido deve ser de no máximo 5MB.');history.go(-1);</script>");
            } else {
                out.println("<script>window.alert('Operação não realizada! Verifique se você realmente escolheu um arquivo e tente novamente, se o problema persistir entre em contato com o Administrador.');history.go(-1);</script>");
            }
        } finally {
            out.close();
        }
    }

    private ServletFileUpload getHandler() throws FileUploadException {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        /*
         *Set the size threshold, above which content will be stored on disk.
         */
        //fileItemFactory.setSizeThreshold(MAX_SIZE_UPLOAD);
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        uploadHandler.setHeaderEncoding(ENCODING);
        uploadHandler.setSizeMax(MAX_SIZE_UPLOAD);

        return uploadHandler;
    }

    private List getItemsRequest(HttpServletRequest request, ServletFileUpload uploadHandler) throws FileUploadException {
        return uploadHandler.parseRequest(request);
    }

    private String getParameter(String fieldName, List items) throws UnsupportedEncodingException {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return new String(item.getString().getBytes("iso-8859-1"), "UTF-8");
                }
            }
        }
        return null;
    }

    private FileItem getFile(String fieldName, List items) {
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase(fieldName)) {
                    return item;
                }
            }
        }
        return null;
    }

    private String getEnderecoRelativoDocumentos(HttpServletRequest request, int codigoCurso) {
        String schema = request.getScheme();
        String porta = request.getServerPort() != 0 ? ":" + request.getServerPort() : "";
        String servidor = request.getServerName();
        String endereco_servidor = schema + "://" + servidor + porta + "/";
        return endereco_servidor + CFG.DIRETORIO_ARQUIVOS + "/" + CFG.DIRETORIO_DOCUMENTOS + "/" + codigoCurso + "/";
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String getPastaDocumentos(int codigoCurso) {
        String root = getServletContext().getRealPath("/");
        String localDocumentos = root.substring(0, root.lastIndexOf(getServletContext().getContextPath().replace("/", System.getProperty("file.separator"))))
                + System.getProperty("file.separator") + CFG.DIRETORIO_ARQUIVOS
                + System.getProperty("file.separator") + CFG.DIRETORIO_DOCUMENTOS
                + System.getProperty("file.separator") + codigoCurso;
        return localDocumentos + System.getProperty("file.separator");
    }
}
